﻿using Prism.Mvvm;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using 基于WPF的电缆采样数据分析系统.Tools.LangugeTool;


namespace 基于WPF的电缆采样数据分析系统.ViewModels.DeviceStatus
{
    public class ColumnOneUCViewModel : BindableBase
    {
        /// <summary>
        /// 构造器
        /// </summary>
        public ColumnOneUCViewModel() {

            // 初始化调度程序定时器
            InitTimer();

            // 初始化设备
            InitDevice();
        }


        #region 时间显示
        /// <summary>
        /// 定义调度程序定时器
        /// </summary>
        private DispatcherTimer _timer = new DispatcherTimer();

        /// <summary>
        /// 初始化调度程序定时器
        /// </summary>
        private void InitTimer()
        {
            // 初始化调度程序定时器
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += Timer_Tick;
            _timer.Start();
        }

        /// <summary>
        /// 时间刷新
        /// </summary>
        private void Timer_Tick(object sender, EventArgs e)
        {
            // CPU使用率更新
            CPUUsageCompute();

            // 可用内存和总物理内存
            AvailableMemoryAndTotalPhysicalMemoryCompute();

            // 电池状态和剩余容量
            BatteryStatusAndResidualCapacityCompute();

            // 可用空间
            FreeSpaceCompute();
        }


        /// <summary>
        /// 初始化设备
        /// </summary>
        private void InitDevice()
        {
            // 系统启动时间
            SystemStartupTimeCompute();

            // 驱动器、驱动器类型、文件系统、总空间、卷标
            DriverAndDriveTypeAndTotalSpaceAndLabelCompute();


            // 操作系统名称、安装日期、注册所有者、系统驱动器、系统目录
            OperatingSystemNameAndInstallationDateAndRegisteredOwnerAndSystemDriverAndSystemDirectoryCompute();
        }
        #endregion


        #region 基本状态

        /// <summary>
        /// CPU使用率
        /// </summary>
        private string _CPUUsage;

        /// <summary>
        /// CPU使用率
        /// </summary>
        public string CPUUsage
        {
            get { return _CPUUsage; }
            set { 
                _CPUUsage = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 可用内存(MB)
        /// </summary>
        private string _AvailableMemory;

        /// <summary>
        /// 可用内存(MB)
        /// </summary>
        public string AvailableMemory
        {
            get { return _AvailableMemory; }
            set { 
                _AvailableMemory = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 总物理内存(GB)
        /// </summary>
        private string _TotalPhysicalMemory;

        /// <summary>
        /// 总物理内存(GB)
        /// </summary>
        public string TotalPhysicalMemory
        {
            get { return _TotalPhysicalMemory; }
            set { 
                _TotalPhysicalMemory = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 系统启动时间
        /// </summary>
        private string _SystemStartupTime;

        /// <summary>
        /// 系统启动时间
        /// </summary>
        public string SystemStartupTime
        {
            get { return _SystemStartupTime; }
            set { 
                _SystemStartupTime = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 电池状态
        /// </summary>
        private string _BatteryStatus;

        /// <summary>
        /// 电池状态
        /// </summary>
        public string BatteryStatus
        {
            get { return _BatteryStatus; }
            set { 
                _BatteryStatus = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 剩余容量
        /// </summary>
        private string _ResidualCapacity;

        /// <summary>
        /// 剩余容量
        /// </summary>
        public string ResidualCapacity
        {
            get { return _ResidualCapacity; }
            set { 
                _ResidualCapacity = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        ///  CPU使用率
        /// </summary>
        PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");


        /// <summary>
        /// CPU使用率更新
        /// </summary>
        private void CPUUsageCompute()
        { 
            CPUUsage = cpuCounter.NextValue().ToString();
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORYSTATUSEX
        {
            public uint dwLength;
            public uint dwMemoryLoad; // 内存使用率
            public ulong ullTotalPhys; // 总物理内存（字节）
            public ulong ullAvailPhys; // 可用物理内存（字节）
            public ulong ullTotalPageFile; // 总页文件
            public ulong ullAvailPageFile; // 可用页文件
            public ulong ullTotalVirtual; // 总虚拟内存
            public ulong ullAvailVirtual; // 可用虚拟内存
            public ulong ullAvailExtendedVirtual; // 扩展虚拟内存
        }

        [DllImport("kernel32.dll")]
        static extern bool GlobalMemoryStatusEx(out MEMORYSTATUSEX lpBuffer);

        /// <summary>
        /// 可用内存和总物理内存
        /// </summary>
        private void AvailableMemoryAndTotalPhysicalMemoryCompute()
        {
            MEMORYSTATUSEX memoryStatus = new MEMORYSTATUSEX();
            memoryStatus.dwLength = (uint)Marshal.SizeOf(memoryStatus);
            GlobalMemoryStatusEx(out memoryStatus);

            AvailableMemory = (memoryStatus.ullAvailPhys / 1024 / 1024).ToString() + " MB";
            TotalPhysicalMemory = (memoryStatus.ullTotalPhys / 1024 / 1024).ToString() + " MB";

        }

       /// <summary>
       /// 系统启动时间
       /// </summary>
        private void SystemStartupTimeCompute()
        {
            // 获取系统启动后经过的毫秒数
            int uptimeMilliseconds = Environment.TickCount;

            // 获取当前时间
            DateTime now = DateTime.Now;

            // 计算启动时间
            TimeSpan uptime = TimeSpan.FromMilliseconds(uptimeMilliseconds);
            DateTime bootTime = now - uptime;

            SystemStartupTime = bootTime.ToString("MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 电池状态和剩余容量
        /// </summary>
        private void BatteryStatusAndResidualCapacityCompute()
        {
            try
            {
                // 查询电池信息
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Battery");

                foreach (ManagementObject battery in searcher.Get())
                {
                    // 获取电池状态
                    uint batteryStatus = Convert.ToUInt32(battery["BatteryStatus"]);
                    string statusDescription = GetBatteryStatusDescription(batteryStatus);

                    // 获取剩余容量
                    uint remainingCapacity = Convert.ToUInt32(battery["EstimatedChargeRemaining"]);

                    BatteryStatus = statusDescription;
                    ResidualCapacity = remainingCapacity + "%";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);
            }
        }



        // 根据电池状态码返回描述
        static string GetBatteryStatusDescription(uint status)
        {
            switch (status)
            {
                case 1:
                    return LangugeConvertor.GetValue("UnknownState");
                case 2:
                    return LangugeConvertor.GetValue("ChargeAndDischarge");
                case 3:
                    return LangugeConvertor.GetValue("FullCharge");
                case 4:
                    return LangugeConvertor.GetValue("LowBatteryWarning");
                case 5:
                    return LangugeConvertor.GetValue("CriticalCharge");
                case 6:
                    return LangugeConvertor.GetValue("BeCharging");
                case 7:
                    return LangugeConvertor.GetValue("ChargeComplete");
                default:
                    return LangugeConvertor.GetValue("OtherStates");
            }
        }

        #endregion


        #region 磁盘信息
        /// <summary>
        /// 驱动器
        /// </summary>
        private string _Driver;

        /// <summary>
        /// 驱动器
        /// </summary>
        public string Driver
        {
            get { return _Driver; }
            set { 
                _Driver = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 驱动器类型
        /// </summary>
        private string _DriveType;

        /// <summary>
        /// 驱动器类型
        /// </summary>
        public string DriveType
        {
            get { return _DriveType; }
            set { 
                _DriveType = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 文件系统
        /// </summary>
        private string _FileSystem;

        /// <summary>
        /// 文件系统
        /// </summary>
        public string FileSystem
        {
            get { return _FileSystem; }
            set { 
                _FileSystem = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 总空间(GB)
        /// </summary>
        private string _TotalSpace;

        /// <summary>
        /// 总空间(GB)
        /// </summary>
        public string TotalSpace
        {
            get { return _TotalSpace; }
            set { 
                _TotalSpace = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 可用空间(GB)
        /// </summary>
        private string _FreeSpace;

        /// <summary>
        /// 可用空间(GB)
        /// </summary>
        public string FreeSpace
        {
            get { return _FreeSpace; }
            set { 
                _FreeSpace = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 卷标
        /// </summary>
        private string _Label;

        /// <summary>
        /// 卷标
        /// </summary>
        public string Label
        {
            get { return _Label; }
            set { 
                _Label = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 驱动器、驱动器类型、文件系统、总空间、卷标
        /// </summary>
        private void DriverAndDriveTypeAndTotalSpaceAndLabelCompute()
        {
            // 获取所有磁盘分区
            DriveInfo[] drives = DriveInfo.GetDrives();

            DriveInfo driveInfo = drives[0];

            if (driveInfo.IsReady) // 确保磁盘已准备好
            {
                Driver = driveInfo.Name;
                FileSystem = driveInfo.DriveFormat;
                TotalSpace = FormatBytes(driveInfo.TotalSize);
                Label = driveInfo.VolumeLabel;
            }
        }


        // 根据磁盘类型返回描述
        static string GetDriveTypeDescription(DriveType type)
        {
            switch ((int)type)
            {
                case 3:
                    return LangugeConvertor.GetValue("LocalDisk");
                case 4:
                    return LangugeConvertor.GetValue("NetworkDriver");
                case 5:
                    return LangugeConvertor.GetValue("OpticalDrive");
                case 2:
                    return LangugeConvertor.GetValue("RemovableDisk");
                case 0:
                    return LangugeConvertor.GetValue("UnknownType");
                default:
                    return LangugeConvertor.GetValue("OtherType");
            }
        }

        // 格式化字节数为人类可读的形式
        static string FormatBytes(long bytes)
        {
            string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
            int index = 0;

            while (bytes >= 1024 && index < suffixes.Length - 1)
            {
                bytes /= 1024;
                index++;
            }

            return $"{bytes} {suffixes[index]}";
        }

        /// <summary>
        /// 可用空间
        /// </summary>
        private void FreeSpaceCompute()
        {
            // 获取所有磁盘分区
            DriveInfo[] drives = DriveInfo.GetDrives();

            DriveInfo driveInfo = drives[0];

            if (driveInfo.IsReady) // 确保磁盘已准备好
            {
                FreeSpace = FormatBytes(driveInfo.AvailableFreeSpace);
                DriveType = GetDriveTypeDescription(driveInfo.DriveType);
            }
        }

        #endregion


        #region 操作系统

        /// <summary>
        /// 操作系统名称
        /// </summary>
        private string _OperatingSystemName;

        /// <summary>
        /// 操作系统名称
        /// </summary>
        public string OperatingSystemName
        {
            get { return _OperatingSystemName; }
            set { 
                _OperatingSystemName = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 安装日期
        /// </summary>
        private string _InstallationDate;

        /// <summary>
        /// 安装日期
        /// </summary>
        public string InstallationDate
        {
            get { return _InstallationDate; }
            set { 
                _InstallationDate = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 注册所有者
        /// </summary>
        private string _RegisteredOwner;

        /// <summary>
        /// 注册所有者
        /// </summary>
        public string RegisteredOwner
        {
            get { return _RegisteredOwner; }
            set { 
                _RegisteredOwner = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 系统目录
        /// </summary>
        private string _SystemDirectory;

        /// <summary>
        /// 系统目录
        /// </summary>
        public string SystemDirectory
        {
            get { return _SystemDirectory; }
            set { 
                _SystemDirectory = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 操作系统名称、安装日期、注册所有者、系统驱动器、系统目录
        /// </summary>
        private void OperatingSystemNameAndInstallationDateAndRegisteredOwnerAndSystemDriverAndSystemDirectoryCompute()
        {
            try
            {
                // 查询操作系统信息
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");

                foreach (ManagementObject os in searcher.Get())
                {
                    OperatingSystemName = os["Caption"].ToString();
                    InstallationDate = ManagementDateTimeConverter.ToDateTime(os["InstallDate"].ToString()).ToString();
                    RegisteredOwner = os["RegisteredUser"].ToString();
                    string[] newStr = os["SystemDirectory"].ToString().Split("\\");
                    SystemDirectory = newStr[newStr.Length - 2] + "\\" + newStr[newStr.Length - 1];
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);
            }

        }

        #endregion

    }
}
